package com.axzh.multithread.download;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * 速度监控，1秒内的平均下载
 * @author wml
 *
 */
public class DLSpeedMonitor {
	private static final int PERIOD = 1000000000;// nano
	private LinkedList<Speed> speedList = new LinkedList<Speed>();
	
	public synchronized void update(int bytes) {
		speedList.add(new Speed(bytes));
		
		long begin = System.nanoTime() - PERIOD;
		
		for (Speed speed : new ArrayList<Speed>(speedList)) {
			if(speed.time >= begin) {
				break;
			}
			speedList.remove(0);
		}
	}
	
	public synchronized int getSpeed() {
		int total = 0;
		long begin = System.nanoTime() - PERIOD;
		for (Speed speed : speedList) {
			if(speed.time >= begin)
				total += speed.bytes;
		}
		return (int) ((double)total / PERIOD * 1000000000);
	}

	class Speed {
		final long time;
		final int bytes;
		Speed(int bytes) {
			this.time = System.nanoTime();
			this.bytes = bytes;
		}
	}
}
